package com.muatocroi.tornado;

import java.net.InetAddress;
import java.util.ArrayList;


import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

public class SettingActivity extends Activity implements OnClickListener{

	ToggleButton tgBtnWebserver;
	TextView txvIP;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_setting);
		
		tgBtnWebserver = (ToggleButton)findViewById(R.id.tgBtnWebserver);
		 txvIP = (TextView) findViewById(R.id.txvServerIP);
		tgBtnWebserver.setOnClickListener(this);
		
		
		if (WebServer.isRunning())
		{
			ArrayList<InetAddress> addr = AddressLocal.getLocals();
			String port = ":" + WebServer.port;
			if (addr.size() > 0)
			{
				txvIP.setText("http:/" + addr.get(0).toString() + port);
				tgBtnWebserver.setChecked(true);
			}
			else
			{
				Toast.makeText(getApplicationContext(),"Lost network connect.", Toast.LENGTH_LONG).show();
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.setting, menu);
		return true;
	}
	@Override
	public void onClick(View arg0) {
		ToggleButton tgBtnWebserver = (ToggleButton)arg0;
		TextView txvIP = (TextView) findViewById(R.id.txvServerIP);
		if (!tgBtnWebserver.isChecked())
		{
			if (WebServer.isRunning()) 
			{
				WebServer.stop();
				txvIP.setText("");
			}	
		}
		else
		{
			ArrayList<InetAddress> addr = AddressLocal.getLocals();
			String port = ":" + WebServer.port;
			if (addr.size() > 0) {
				if (WebServer.start(this)) {
					txvIP.setText("http:/" + addr.get(0).toString() + port);
				} else {
					Toast.makeText(getApplicationContext(),"Can't start web server!", Toast.LENGTH_LONG).show();
				}
			} else {
				Toast.makeText(getApplicationContext(),"no local network!",Toast.LENGTH_LONG).show();
			}
		}
		tgBtnWebserver.setChecked(WebServer.isRunning());
	}

}
